package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;


@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录
     * @param dto
     * @return
     */
    public ResponseResult login(AdUserDto dto){
        // 判断 参数
        if (dto==null){
            CatchCustomException.catchs(20003,"参数不合法");
        }
        // 判断 参数是否有空值
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            CatchCustomException.catchs(20004,"用户名或密码为空");
        }
        // 根据name 查找数据
        AdUser adUser =  this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,dto.getName()));

        // 判断  数据库没有该name
        if (adUser==null){
            CatchCustomException.catchs(20005,"用户名错误");
        }

        // 判断  账号状态
        if (adUser.getStatus()!=9){
            CatchCustomException.catchs(20006,"账号异常");
        }
//         判断 密码是否正确
        if (!BCrypt.checkpw(dto.getPassword(),adUser.getPassword())){
            CatchCustomException.catchs(20007,"密码错误");
        }


        // 修改最后登录时间
        adUser.setLoginTime(new Date());
        updateTime(adUser);
        // 签发令牌

        String token = AppJwtUtil.getToken(Long.parseLong(adUser.getId() + ""));
        HashMap<String, Object> hashMap = new HashMap<>();
          adUser.setPassword("");
          hashMap.put("user",adUser);
          hashMap.put("token",token);
        return  ResponseResult.okResult(hashMap);
    }

    @Override
    public ResponseResult mes(Integer id) {
        if (id==null){
            CatchCustomException.catchs(20003,"参数不合法");
        }
        AdUser adUser = this.getById(id);
        adUser.setPassword("");
        return  ResponseResult.okResult(adUser);
    }

    @Transactional
    public void  updateTime(AdUser adUser){
        this.updateById(adUser);
    }
}
